<template>
  <!-- 最外层：只负责水平居中 -->
    <div class="page-fix">
      <!-- 唯一可滚动容器：van-pull-refresh 自己 -->
      <van-pull-refresh
        class="scroll-refresh"
        v-model="refreshing"
        @refresh="onRefresh"
      >
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :immediate-check="false"
        >
          <VantTable :data="tableData" @selection-change="handleSelection" @barcode-click="onBarcodeClick" />
        </van-list>
      </van-pull-refresh>

      <!-- 底部按钮 -->
      <!-- <van-button class="bottom-btn" type="primary" block @click="onCreateCode">生成条码</van-button> -->
    </div>

  <!-- 搜索气泡 -->
  <van-floating-bubble
    v-model:offset="bubbleOffset"
    axis="xy"
    icon="search"
    magnetic="x"
    @click="showSearch = true"
  />

  <!-- 居中弹窗 -->
  <van-popup
    v-model:show="showSearch"
    position="center"
    class="search-dialog"
    round
    closeable
  >
    <div class="search-wrapper">
      <div class="search-title">查询单据信息</div>

      <!-- 供应商 -->
      <van-field
        v-model="form.supplier"
        label="供应商"
        label-width="120"
        placeholder="请选择供应商"
        input-align="right"
        is-link
        readonly
        @click="showSupplierPicker = true"
      >
        <template #right-icon v-if="form.supplier">
          <van-icon name="clear" @click.stop="clearSupplier" />
        </template>
      </van-field>
      <!-- 批号 -->
      <van-field 
        v-model="form.batchNo" 
        label="批号" 
        label-width="120" 
        input-align="right" 
        placeholder="请输入批号"
      >
        <template #right-icon v-if="form.batchNo">
          <van-icon name="clear" @click="clearBatchNo" />
        </template>
      </van-field>
      <!-- 业务类型 -->
      <van-field
        v-model="form.bizType"
        label="业务类型"
        label-width="120"
        placeholder="点击选择业务类型"
        input-align="right"
        is-link
        readonly
        @click="showBizTypePicker = true"
      >
        <template #right-icon v-if="form.bizType">
          <van-icon name="clear" @click.stop="clearBizType" />
        </template>
      </van-field>
      <!-- 检验日期区间 -->
      <van-cell
        title="检验日期区间"
        label-width="120"
        :value="dateLabel.inspect"
        is-link
        @click="showCalendarInspect = true"
      >
        <template #right-icon v-if="dateLabel.inspect">
          <van-icon name="clear" class="clear-btn" @click.stop="clearInspectDate" />
        </template>
      </van-cell>
      <!-- 生产日期区间 -->
      <van-cell
        title="生产日期区间"
        label-width="120"
        :value="dateLabel.product"
        is-link
        @click="showCalendarProduct = true"
      >
        <template #right-icon v-if="dateLabel.product">
          <van-icon name="clear" class="clear-btn" @click.stop="clearProductDate" />
        </template>
      </van-cell>

      <!-- 按钮组 -->
      <div class="button-group">
        <van-button type="primary" round @click="onQuery">确认</van-button>
        <van-button type="default" round @click="onReset">重置</van-button>
      </div>
    </div>
  </van-popup>

  <!-- 下面 4 个弹层（日历、picker）继续复用刚才写的，不用动 -->
  <van-calendar
    v-model:show="showCalendarInspect"
    type="range"
    :min-date="new Date('2020-01-01')"
    @confirm="onConfirmInspect"
  />
  <van-calendar
    v-model:show="showCalendarProduct"
    type="range"
    :min-date="new Date('2020-01-01')"
    @confirm="onConfirmProduct"
  />
  <!-- 可搜索的供应商选择器 -->
  <van-popup v-model:show="showSupplierPicker" position="bottom" round @open="onSupplierPanelOpen">
    <!-- 1. 搜索框 -->
    <van-search
      v-model="supplierKw"
      placeholder="请输入供应商名称"
      clearable
      show-action
      @search="onSearchSupplier"
      @clear="onSearchSupplier"
      @input="onSearchSupplier"
    >
      <template #action>
        <span @click="showSupplierPicker = false">取消</span>
      </template>
    </van-search>

    <!-- 2. 搜索结果列表（用 van-picker 展示） -->
    <van-picker
      v-if="supplierSearchList.length"
      :columns="supplierSearchList"
      :columns-field-names="{ text: 'text', value: 'text' }"
      @confirm="onPickSupplier"
      @cancel="showSupplierPicker = false"
    />
    <!-- 3. 空状态 -->
    <van-empty v-else description="暂无匹配供应商" />
  </van-popup>
  <van-popup v-model:show="showBizTypePicker" position="bottom">
    <van-picker
      :columns="bizTypeCols"
      :columns-field-names="{ text: 'text', value: 'value' }"
      @confirm="pickBizType"
      @cancel="showBizTypePicker = false"
    />
  </van-popup>

  <!-- 生成条码弹窗 -->
  <van-popup
    v-model:show="showQrcode"
    position="center"
    closeable
    class="qrcode-dialog"
  >
    <div class="qrcode-wrapper">
      <!-- 左侧二维码 -->
      <div class="qrcode-left">
        <qrcode-vue :value="qrcodeText" :size="180" level="H" />
      </div>

      <!-- 右侧信息 -->
      <div class="qrcode-right">
        <div>存货编码：{{ qrcodeRow['存货编码'] }}</div>
        <div>供应商：{{ qrcodeRow['供应商名称'] }}</div>
        <div>检验日期：{{ qrcodeRow['检验日期'] }}</div>
        <div>生产日期：{{ qrcodeRow['生产日期'] }}</div>
        <div>批号：{{ qrcodeRow['批号'] }}</div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="qrcode-footer">
      <van-button class="qr-btn" type="primary" @click="onScanDone">完成扫描</van-button>
      <van-button class="qr-btn" type="danger" @click="onScanCancel">取消扫描</van-button>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, onMounted, nextTick, reactive } from "vue";
import { showFailToast, showToast, showDialog } from "vant";
import axios from "axios";
import VantTable from "@/components/VantTable.vue";
import QrcodeVue from 'qrcode.vue'

// 配置axios基础URL
const API_BASE_URL = import.meta.env.DEV 
  ? '/api' // 开发环境使用Vite代理，需要/api前缀
  : 'http://192.168.12.253:82/api'; // 生产环境通过nginx访问

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器
api.interceptors.request.use(
  config => {
    console.log('API请求:', config.method?.toUpperCase(), config.url, config.data);
    return config;
  },
  error => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 添加响应拦截器
api.interceptors.response.use(
  response => {
    console.log('API响应:', response.status, response.data);
    return response;
  },
  error => {
    console.error('API错误:', error.message);
    return Promise.reject(error);
  }
);

/* 二维码 */
const showQrcode   = ref(false)
const qrcodeText   = ref('')   // 二维码内容
const qrcodeRow    = ref({})   // 当前选中的行

/* 点击单据条码 */
function onBarcodeClick(row) {
  // 单选：把这一行当成“已选”
  selected.value = [row]
  // 后面完全复用原来逻辑
  onCreateCode()
}

/* 点击「生成条码」 */
function onCreateCode() {
  if (!selected.value.length) {
    showDialog({ message: '请先选择一条数据' })
    return
  }
  // selected 是 VantTable 抛出的数组，单选所以取 0
  const row = selected.value[0]
  qrcodeText.value = row['单据条码']
  qrcodeRow.value  = row
  showQrcode.value = true
}

/* 完成扫描 */
async function onScanDone() {
  showQrcode.value = false;          // 关闭二维码弹窗
  showToast('扫描完成');             // 轻提示

  /* ---------- 回写后端 ---------- */
  if (!selected.value.length) return;          // 保险：没数据就不走接口
  const codes = selected.value.map(r => r['单据条码']);

  try {
    await api.post('/markScanned', { barcodes: codes });
  } catch (e) {
    showFailToast('状态回写失败，请重试');
    return;        // 回写失败就不再刷新列表
  }

  /* ---------- 刷新列表 ---------- */
  finished.value = false;
  page.value = 1;
  tableData.value = [];
  refreshing.value = true;
  await onRefresh();   // 重新拉取第一页数据
}

/* 取消扫描 */
async function onScanCancel() {
  showQrcode.value = false;          // 关闭二维码弹窗
  showToast('已取消扫描');           // 轻提示

  if (!selected.value.length) return;
  const codes = selected.value.map(r => r['单据条码']);

  try {
    /* 新增接口：把状态置成 0 */
    await api.post('/markUnScanned', { barcodes: codes });
  } catch (e) {
    showFailToast('状态回写失败，请重试');
    return;
  }

  /* 刷新列表（同完成扫描） */
  finished.value = false;
  page.value = 1;
  tableData.value = [];
  refreshing.value = true;
  await onRefresh();
}

/* ----------- 原有业务数据 ----------- */
const tableData = ref([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const page = ref(1);
const pageSize = 100;
const selected = ref([]);

const showSearch = ref(false); // 主弹层
const showCalendarInspect = ref(false); // 检验日期
const showCalendarProduct = ref(false); // 生产日期
const showSupplierPicker = ref(false); // 供应商
const showBizTypePicker = ref(false); // 业务类型


/* ------------ 表单数据 ------------ */
const form = reactive({
  supplier: "",
  batchNo: "",
  bizType: "",
});

/* ------------ 查询条件（统一放这里）------------ */
const query = reactive({
  inspectionDateStart: '',
  inspectionDateEnd: '',
  produceDateStart: '',
  produceDateEnd: '',
  batchNo: '',
  bizType: '',
  vendorName: ''
})

/* ------------ 日期区间文字展示 ------------ */
const dateLabel = reactive({
  inspect: "",
  product: "",
});


/* ===== 实时搜索 ===== */
let searchTimer = null
function onSearchSupplier() {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(async () => {
    const kw = supplierKw.value.trim()
    try {
      // ① 改为 POST，② 空串也能走，后端 LIKE '%%' 会返回全部
      const { data } = await api.post('/vendor', { kw })
      supplierSearchList.value = data.map(name => ({ text: name, value: name }))
    } catch {
      supplierSearchList.value = []
    }
  }, 300)
}

function onSupplierPanelOpen() {
  supplierKw.value = ''        // 清空输入框
  onSearchSupplier()           // 立即加载全部
}

/* ===== 选中回调 ===== */
function onPickSupplier({ selectedOptions }) {
  form.supplier = selectedOptions[0].text
  showSupplierPicker.value = false
}


/* ------------ 选择器列数据（示例） ------------ */
/* ===== 响应式变量 ===== */
const supplierKw = ref('')                 // 搜索关键字
const supplierSearchList = ref([])         // 接口返回的列表面


const bizTypeCols = [
  { text: "来料检验", value: 1 },
  { text: "委外检验", value: 2 },
  { text: "生产检验", value: 3 },
];

/* 业务类型文本 → 后端枚举 */
const BIZ_MAP = {
  来料检验: 'ARR',
  委外检验: 'SUB',
  生产检验: 'PRO'
}

function pickSupplier({ selectedOptions }) {
  form.supplier = selectedOptions[0].text   // 或 selectedOptions[0].value 看你想要什么
  showSupplierPicker.value = false
}

function pickBizType({ selectedOptions }) {
  const txt = selectedOptions[0].text
  form.bizType = txt                       // 界面展示仍用中文
  query.bizType = BIZ_MAP[txt] || ''       // 真正传给后端的枚举
  showBizTypePicker.value = false
}
/* ------------ 日期确认回调 ------------ */
const formatDate = (d) => {
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
const formatDisplayDate = (d) => `${d.getMonth() + 1}/${d.getDate()}`;

function onConfirmInspect(values) {
  const [start, end] = values;
  showCalendarInspect.value = false;
  dateLabel.inspect = `${formatDisplayDate(start)} - ${formatDisplayDate(end)}`;
  // 同时更新查询条件为标准格式
  query.inspectionDateStart = formatDate(start);
  query.inspectionDateEnd = formatDate(end);
}
function onConfirmProduct(values) {
  const [start, end] = values;
  showCalendarProduct.value = false;
  dateLabel.product = `${formatDisplayDate(start)} - ${formatDisplayDate(end)}`;
  // 同时更新查询条件为标准格式
  query.produceDateStart = formatDate(start);
  query.produceDateEnd = formatDate(end);
}

function onQuery() {
  /* 真正给后端的查询参数 */
  // 日期参数已经在 onConfirmInspect/onConfirmProduct 中设置好了，这里不需要再解析
  query.batchNo             = form.batchNo || ''
  query.vendorName          = form.supplier || ''

  /* ===== 关键：把中文转成枚举再赋值 ===== */
  query.bizType = BIZ_MAP[form.bizType] || ''

  /* 关闭弹窗 & 刷新列表 */
  showSearch.value = false
  finished.value   = false
  refreshing.value = true
  tableData.value  = []
  page.value       = 1
  onRefresh()
}

/* 重置表单 */
function onReset() {
  form.supplier = ''
  form.batchNo = ''
  form.bizType = ''
  dateLabel.inspect = ''
  dateLabel.product = ''
  
  // 清空查询条件
  Object.keys(query).forEach(key => {
    query[key] = ''
  })
  
  showToast('表单已重置')
}

/* 清空供应商 */
function clearSupplier() {
  form.supplier = ''
}

/* 清空批号 */
function clearBatchNo() {
  form.batchNo = ''
}

/* 清空业务类型 */
function clearBizType() {
  form.bizType = ''
  query.bizType = ''
}

/* 清空检验日期 */
function clearInspectDate() {
  dateLabel.inspect = ''
  query.inspectionDateStart = ''
  query.inspectionDateEnd = ''
}

/* 清空生产日期 */
function clearProductDate() {
  dateLabel.product = ''
  query.produceDateStart = ''
  query.produceDateEnd = ''
}

function handleSelection(rows) {
  selected.value = rows;
}

/* ----------- 浮动气泡 ----------- */
// 先给一个“安全”初值，避免 TS/模板报错
const bubbleOffset = ref({ x: 0, y: 0 });
onMounted(async () => {
  await nextTick();
  bubbleOffset.value = {
    x: window.innerWidth - 172,
    y: window.innerHeight - 172,
  };
  // 手动触发首次数据加载
  onRefresh();
});
function onOffsetChange(offset) {
  // 拖拽过程中实时回调，这里简单 toast 一下，也可去掉
  // showToast(`x: ${offset.x.toFixed(0)}, y: ${offset.y.toFixed(0)}`)
}

/* ----------- 列表逻辑 ----------- */
async function onLoad() {
  try {
    const { data } = await api.post("/query", {
      page: page.value,
      size: pageSize,
      ...query          // 一键展开所有查询条件
    });
    const rows = data.list ?? [];
    if (rows.length) {
      tableData.value.push(...rows);
      page.value++;
    } else {
      finished.value = true;
    }
  } catch (error) {
    console.error('API请求失败:', error);
    showFailToast("加载失败，请检查网络连接");
    finished.value = true; // 避免无限重试
  } finally {
    loading.value = false;
    refreshing.value = false
  }
}

async function onRefresh() {
  finished.value = false;
  page.value = 1;
  tableData.value = [];
  await onLoad();
  refreshing.value = false;
}
</script>

<style scoped>
/* ---------- 页面整体 ---------- */
html,
body {
  margin: 0;
  height: 100%;
}
.page-fix {
  height: 100vh;
  display: flex;
  flex-direction: column;
}


/* ---------- 关键：让 van-pull-refresh 本身滚动 ---------- */
.scroll-refresh {
  flex: 1; /* 吃掉剩余高度 */
  overflow-y: auto; /* 竖向可滚 */
  border: 3px solid #ebedf0; /* 添加边框 */
}

.my-bubble {
  --van-floating-bubble-size: 100px;
  --van-floating-bubble-icon-size: 50px; /* 任意尺寸 */
}

/* 弹窗本身：白色背景 + 圆角 + 阴影 */
.search-dialog {
  width: 50vw;
  max-width: 600px;
  max-height: 90vh;          /* ① 关键：不要写死 30vh */
  background: #fff; /* ① 背景 */
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  --van-cell-font-size: 14px;      /* 减小单元格、field、cell 字体大小 */
  --van-button-normal-font-size: 14px;  /* 减小按钮字体大小 */
  padding: 20px;/* 弹窗的内边距 */
}

/* 内容区：直接给固定高度，避免flex:1被压缩 */
.search-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;      /* 每行之间 20 px */
  padding: 20px;
  overflow-y: auto;   /* 内容过多时内部滚动 */
}
/* 标题美化 */
.search-title {
  font-size: 16px;    /* 减小标题字体大小 */
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  gap: 15px;
}

.button-group .van-button {
  flex: 1;
}

/* 统一清空按钮样式 - 提高优先级 */
.search-dialog .van-field .van-icon[name="clear"],
.search-dialog .van-cell .van-icon[name="clear"],
.search-dialog .van-icon[name="clear"],
.search-dialog .clear-btn {
  color: #c8c9cc !important;
  font-size: 16px !important;
  padding: 4px !important;
  cursor: pointer;
  transition: color 0.2s ease !important;
  width: 20px !important;
  height: 20px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

.search-dialog .van-field .van-icon[name="clear"]:hover,
.search-dialog .van-cell .van-icon[name="clear"]:hover,
.search-dialog .van-icon[name="clear"]:hover,
.search-dialog .clear-btn:hover {
  color: #969799 !important;
}

/* 强制覆盖 Vant 默认样式 */
.search-dialog .van-field__right-icon .van-icon,
.search-dialog .van-cell__right-icon .van-icon,
.search-dialog [class*="right-icon"] .van-icon {
  color: #c8c9cc !important;
  font-size: 16px !important;
}

/* 额外确保所有图标都是统一颜色 */
.search-dialog .van-icon {
  color: #c8c9cc !important;
}

/* 二维码相关*/
/* 二维码弹窗 */
.qrcode-dialog {
  max-width: 55vw;
  width: 50vw;
  max-height: 85vh;
  height: auto;        /* 改为自适应高度 */
  padding: 3vh;        /* 减少内边距 */
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.qrcode-wrapper {
  display: flex;
  gap: 2em; /*减少二维码和内容之间的间距*/
  margin-bottom: 2em; /*减少按钮和内容之间的间距*/
  align-items: center; /*垂直居中对齐*/
}
.qrcode-left {
  flex-shrink: 0;
}
.qrcode-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  font-size: 14px;    /* 进一步减小二维码信息字体大小 */
  line-height: 1.4;   /* 进一步减小行高 */
  gap: 0.5em;         /* 添加行间距控制 */
}
.qrcode-footer {
  display: flex;
  gap: 2em;         /* 减少按钮间距 */
  margin-top: 1em;  /* 添加顶部间距 */
}

/* 底部按钮样式：添加上下 margin，水平居中 */
.qr-btn {
  width: 25vh;       /* 减小按钮宽度 */
  height: 50px;      /* 减小按钮高度 */
  flex: none;
  font-size: 16px;   /* 进一步减小按钮字体大小 */
  border-radius: 8px; /* 减小圆角 */
  font-weight: bold; /* 字体加粗 */
}

</style>
